<?php
namespace Sfsn\Core\Schema;

class ColumnSchema
{
    /**
     * 字段名称
     * @var unknown
     */
    public $name;
    /**
     * 是否可以为NULL
     * @var unknown
     */
    public $allowNull;

    /**
     * 字段的类型
     * @var unknown
     */
    public $type;
    /**
     * 字段类型对应的PHP数据类型
     * @var unknown
     */
    public $phpType;
    /**
     * 数据库生成的类型如varchar(255)
     * @var unknown
     */
    public $dbType;
    /**
     * 字段默认值
     * @var unknown
     */
    public $defaultValue;
    /**
     * 若字段为枚举类型，该属性用于表示可供枚举的值
     * @var unknown
     */
    public $enumValues;
    /**
    * 长度
    * @var unknown
    */
    public $size;

    public $precision;
    /**
     * 若字段为数值，该属性用于表示精度
     * @var unknown
     */
    public $scale;

    /**
     * 是否是主键
     * @var unknown
     */
    public $isPrimaryKey;
    /**
     * 是否是自增长字段
     * @var unknown
     */
    public $autoIncrement = false;
     /**
      * 是否是unsigned，仅对支持的类型有效
      * @var unknown
      */
    public $unsigned;
    /**
     * 字段描述信息
     * @var unknown
     */
    public $comment;
 
    /**
     * Converts the input value according to [[phpType]] after retrieval from the database.
     * If the value is null or an [[Expression]], it will not be converted.
     * 
     * @param mixed $value
     *            input value
     * @return mixed converted value
     */
    public function phpTypecast($value)
    {
        if ($value === '' && $this->type !== Schema::TYPE_TEXT && $this->type !== Schema::TYPE_STRING && $this->type !== Schema::TYPE_BINARY) {
            return null;
        }
        if ($value === null || gettype($value) === $this->phpType) {
            return $value;
        }
        switch ($this->phpType) {
            case 'resource':
            case 'string':
                return is_resource($value) ? $value : (string) $value;
            case 'integer':
                return (int) $value;
            case 'boolean':
                return (bool) $value;
            case 'double':
                return (double) $value;
        }
        return $value;
    }

    /**
     * Converts the input value according to [[type]] and [[dbType]] for use in a db query.
     * If the value is null or an [[Expression]], it will not be converted.
     * 
     * @param mixed $value
     *            input value
     * @return mixed converted value. This may also be an array containing the value as the first element
     *         and the PDO type as the second element.
     */
    public function dbTypecast($value)
    {
        // the default implementation does the same as casting for PHP but it should be possible
        // to override this with annotation of explicit PDO type.
        return $this->phpTypecast($value);
    }
}

